import {MessageBox} from 'element-ui'

// 计算滚动条宽度
function getScrollbarWidth() {
    let outer = document.createElement('div'), widthNoScroll, inner, widthWithScroll, scrollBarWidth
    outer.className = 'el-scrollbar__wrap'
    outer.style.visibility = 'hidden'
    outer.style.width = '100px'
    outer.style.position = 'absolute'
    outer.style.top = '-9999px'
    document.body.appendChild(outer)

    widthNoScroll = outer.offsetWidth
    outer.style.overflow = 'scroll'

    inner = document.createElement('div')
    inner.style.width = '100%'
    outer.appendChild(inner)

    widthWithScroll = inner.offsetWidth
    outer.parentNode.removeChild(outer)
    scrollBarWidth = widthNoScroll - widthWithScroll
    return scrollBarWidth
}

// 返回滚动条隐藏样式
function getScrollbarStyle() {
    return [{
        'margin-right': '-' + getScrollbarWidth() + 'px',
        'margin-bottom': '-' + getScrollbarWidth() + 'px'
    }]
}

// 指定数组删除
function defaultArrayRemove(arr, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === val) {
            arr.splice(i, 1)
            break
        }
    }
    return arr
}

// eval
function evil(fn) {
    let Fn = Function // 一个变量指向Function，防止有些前端编译工具报错
    return new Fn('return ' + fn)()
}

// 获取链接参数
function getParam(url) {
    let locate, baseUrl, query, obj = {}, param
    if (url) {
        let urlList = url.split('?')
        baseUrl = urlList[0]
        query = urlList[1]
    } else {
        locate = window.location
        baseUrl = locate.origin + locate.pathname
        query = locate.search.substr(1)
    }
    if (query) {
        param = query.split('&')
        for (let i = 0; i < param.length; i++) {
            param[i] = param[i].split('=')
            if (param[i][1]) obj[param[i][0]] = param[i][1]
        }
    }
    return {
        url: baseUrl,
        param: obj
    }
}

// 获取浏览器类型
function getBrowserType(type) {
    let browserType = {
        isFirefox: false,
        isOpera: false,
        isChrome: false,
        isEdge: false,
        isSafari: false,
        isIE: false
    }
    var userAgent = navigator.userAgent // 取得浏览器的userAgent字符串

    if (userAgent.indexOf('Firefox') > -1) {
        browserType.isFirefox = true
    } else if (userAgent.indexOf('Edge') > -1) {
        browserType.isEdge = true
    } else if (userAgent.indexOf('Opera') > -1 || userAgent.indexOf('OPR') > -1) {
        browserType.isOpera = true
    } else if (userAgent.indexOf('Chrome') > -1) {
        browserType.isChrome = true
    } else if (userAgent.indexOf('Safari') > -1) {
        browserType.isSafari = true
    } else if (userAgent.indexOf('MSIE') > -1 || userAgent.indexOf('Trident') > -1) {
        browserType.isIE = true
    }
    return type ? browserType[type] : browserType
}

/*
* 存放全局公用方法
*/
export default {
    // 判断是否为array数组
    isArrayFn(value) {
        if (typeof Array.isArray === 'function') {
            return Array.isArray(value)
        } else {
            return Object.prototype.toString.call(value) === '[object Array]'
        }
    },
    // 获取url中指定参数
    getUrlParam(name) {
        let locate = getParam()
        if (locate.param[name]) return locate.param[name]
        return null
    },
    // 改变url中指定参数
    changeUrlArg(url, name, value) {
        let pattern = name + '=([^&]*)', replaceText = name + '=' + value
        return url.match(pattern) ? url.replace(evil('/(' + name + '=)([^&]*)/gi'), replaceText) : (url.match('?') ? url + '&' + replaceText : url + '?' + replaceText)
    },
    // 删除url中指定参数
    delUrlParam(url, name) {
        let locate = getParam(url), newUrl, param
        delete locate.param[name]
        param = JSON.stringify(locate.param).replace(/["{}]/g, '').replace(/[:]/g, '=').replace(/[,]/g, '&')
        newUrl = param ? (locate.url + '?' + param) : locate.url
        return newUrl
    },
    // 全局滚动条更新样式
    updateScrollbarStyle() {
        if (window.Scrollbar && window.Scrollbar[0]) {
            window.Scrollbar.forEach(e => {
                e.sidebarStyle = getScrollbarStyle()
            })
        }
    },
    // 添加Scrollbar对象
    addScrollbar(obj) {
        if (window.Scrollbar) {
            window.Scrollbar.push(obj)
        } else {
            window.Scrollbar = [obj]
        }
    },
    // 删除Scrollbar对象
    removeScrollbar(obj) {
        defaultArrayRemove(window.Scrollbar, obj)
    },
    // 滚动条刷新
    updateView(reset, isSub, vim, obj) {
        // reset 是否不重置滚动条高度，默认false需要重置
        // isSub 是否子页面
        if (!vim) {
            vim = window.$vm
            if (isSub) {
                obj = window.$vm.subMain
            } else {
                obj = window.$vm.main
            }
        }
        vim.$nextTick(() => {
            if (obj) {
                obj.$children[0].update()
                if (!reset) {
                    vim.$nextTick(() => {
                        obj.$el.children[0].scrollTop = 0
                    })
                }
            }
        })
    },
    // 页面返回
    historyBack() {
        let route = window.$vm.$route, router = window.$vm.$router
        if (window.history.length < 2 || window.$history < 2) {
            router.push(route.matched[route.matched.length - 2].path)
        } else {
            router.back(-1)
        }
    },
    // 处理tree数据,data为原始list数据
    treeProcess(data) {
        let list = [], list1 = [], dataList = []
        if (data[0]) {
            data.sort((a, b) => {
                return b.id - a.id
            })
            data.forEach(item => {
                if (!item.label) {
                    item.label = item.abbreviation || item.name
                }
                if (item.parentId) {
                    if (list[item.id]) list[item.id].parentId = item.parentId
                    if (list[item.parentId]) {
                        list[item.parentId].children.push(item)
                    } else {
                        list[item.parentId] = {children: [item]}
                    }
                } else {
                    dataList.push(item)
                }
            })
        }
        list1 = [...list]
        list1.sort((a, b) => {
            return b.children[0].parentId - a.children[0].parentId
        })
        list1.filter(item => {
            if (list[item.children[0].parentId]) {
                if (list[item.parentId]) {
                    list[item.parentId].children.map(obj => {
                        if (obj.id === item.children[0].parentId) {
                            obj.children = list[item.children[0].parentId].children
                        }
                        return obj
                    })
                    delete list[item.children[0].parentId]
                }
            }
            return item
        })
        dataList.forEach(item => {
            if (list[item.id]) item.children = list[item.id].children
        })
        return dataList
    },
    /*
    * 简单弹窗提示
    * type 弹窗类型 message 提示信息 title 弹窗标题（默认为提示）
    * closeOnClickModal 点击遮罩是否关闭弹窗，默认true(type为alert时默认为false)
    * closeOnPressEscape 点击esc键是否关闭弹窗，默认true(type为alert时默认为false)
    * okButton 确认按钮文本内容 cancelButton 取消按钮文本内容（默认设定传了取消按钮文本就显示取消按钮，否则按type类型默认来） showConfirmButton 是否显示确认按钮（默认为true）
    */
    messageBox(type, message, title = '提示', closeOnClickModal, closeOnPressEscape, okButton, cancelButton, showConfirmButton) {
        MessageBox[type](message, title, {
            confirmButtonText: okButton,
            cancelButtonText: cancelButton,
            showConfirmButton: showConfirmButton,
            showCancelButton: cancelButton,
            closeOnClickModal: closeOnClickModal,
            closeOnPressEscape: closeOnPressEscape,
            callback: action => {
            }
        })
    },
    getScrollbarWidth,
    getScrollbarStyle,
    defaultArrayRemove,
    getParam,
    getBrowserType
}
